package org.csu.mypetstore.web.servlets;

import org.csu.mypetstore.domain.Account;
import org.csu.mypetstore.domain.Cart;
import org.csu.mypetstore.service.CartService;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.IOException;

public class ViewCartServlet extends HttpServlet {

    private static final String VIEW_CART = "/WEB-INF/jsp/cart/Cart.jsp";
    private static final String ERROR = "/WEB-INF/jsp/common/Error.jsp";
    private CartService cartService;
    private String userId;

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        cartService = new CartService();
        HttpSession session = request.getSession();
        if (session.getAttribute("account") == null)
        {
            session.setAttribute("message", "Please Sign In At First!");
            request.getRequestDispatcher(ERROR).forward(request, response);
        }
        else
        {
            Account account = (Account)session.getAttribute("account");
            Cart cart = cartService.getCartByUserId(account.getUsername());
            if (cart == null)
                cart = new Cart();
            session.setAttribute("cart", cart);


            request.getRequestDispatcher(VIEW_CART).forward(request, response);

        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }
}
